﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using Jungle.Code.Utils;
using Jungle.News;

namespace Jungle.News.WebControls
{
    public class VNList : WebControl
    {
        protected override void RenderContents(HtmlTextWriter writer)
        {
            NewObject news = new NewObject();
            news.GetAllInList();

            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.Write("<strong>Новости:</strong>");
            writer.RenderEndTag();
            int c = 0;
            foreach(NewObject n in news.NewsLisr)
            {
                writer.AddAttribute("class", "div_VNList_el");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write("<strong>" + n.PubDate.ToShortDateString() + " - " + n.Title + "</strong><br/>");
                writer.Write(CreatePreText(n.Description, 100));
                writer.Write("...");
                writer.AddAttribute(HtmlTextWriterAttribute.Href, UrlHelper.GetSiteUrl() + "/ru/new.aspx?i=" + n.NewId.ToString());
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write("читать дальше");
                writer.RenderEndTag();
                writer.RenderEndTag();
                if (c == 1) break;
                c++;
            }
            base.RenderContents(writer);
        }

        private string CreatePreText(string input, int lenght)
        {
            input = Regex.Replace(input, "<[^>]*?>", string.Empty, RegexOptions.IgnoreCase);
            if(input.Length > lenght)
                input = input.Substring(0, lenght);
            if(input.IndexOf(" ") != -1)
                input = input.Substring(0, input.LastIndexOf(" "));

            return input;
        }

        private HtmlTextWriter PrintImage(HtmlTextWriter writer, string imgUrl)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src, UrlHelper.GetSiteUrl() + imgUrl);
            writer.AddAttribute(HtmlTextWriterAttribute.Align, "absmiddle");
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag();
            return writer;
        }
    }
}
